import React, { useState, useEffect } from 'react';
import AnimatedTransition from '../AnimatedTransition';
import './styleCss/CatesList.scss';
import { SearchBar, Button, Dialog } from 'antd-mobile';
import api from '../axios/index';
import CommonPullToRefresh from '../compages/CommonPullToRefresh';

const CatesList = () => {
    const [catesList, setCatesList] = useState([]);
    const [search, setSearch] = useState('');
    const [filteredList, setFilteredList] = useState([]);
    const [otherHide, setOtherHide] = useState(false); //是否隐藏其他组件

    const getList = async () => {
        const res = await api.get('/list');
        if (res.data.code === 200) {
            setCatesList(res.data.data);
            setFilteredList(res.data.data);
        }
    }

    useEffect(() => {
        getList();
    }, []);

    // 删除商品
    const handleDelete = async (id) => {
        if (!window.confirm('确定要删除吗?')) return;
        try {
            const res = await api.delete(`/delete/${id}`);
            if (res.data.code === 200) {
                getList();
            } else {
                alert(res.data.message || '删除失败');
            }
        } catch (err) {
            alert('删除失败');
        }
    }

    // 搜索过滤
    useEffect(() => {
        if (!search) {
            setFilteredList(catesList);
        } else {
            setFilteredList(
                catesList.filter(item =>
                    (item.title && item.title.includes(search)) ||
                    (item.context && item.context.includes(search))
                )
            )
        }
    }, [search, catesList]);

    // 封装一个字符串截断函数
    const truncateText = (text, maxLength = 5) => {
        if (!text) return '';
        return text.length > maxLength ? text.slice(0, maxLength) + '...' : text;
    }

    return (
        <AnimatedTransition>
            <CommonPullToRefresh
                onRefresh={(async () => {
                    // 这里可以加2秒延迟模拟
                    await new Promise(res => setTimeout(res, 2000));
                    await getList();
                })}
                hideOnRefresh={
                    !otherHide && (
                        <div className="cates-list-search">
                            <SearchBar
                                placeholder='请输入商品名称或描述'
                                value={search}
                                onChange={val => setSearch(val)}
                                showCancelButton
                                onCancel={() => setSearch('')}
                            />
                        </div>
                    )
                }
            >
                <div className="cates-list-grid">
                    {
                        filteredList.length === 0 ? (
                            <div className="cates-list-empty">暂无匹配商品</div>
                        ) : (
                            filteredList.map((item, index) => {
                                return (
                                    <div key={item.id || idx} className="cates-list-item">
                                        <div className="cates-list-images">
                                            {
                                                item.images && item.images.length > 0 ? (
                                                    <img
                                                        src={item.images[0]}
                                                        alt="商品图片"
                                                        className="single-img" />
                                                ) : (
                                                    <span>无图片</span>
                                                )
                                            }
                                        </div>
                                        <div>名称：{truncateText(item.title)}</div>
                                        <div>描述：{truncateText(item.context)}</div>
                                        <div>价格：{item.price}</div>
                                        <div className='cates-list-btns'>
                                            <Button
                                                onClick={() => {
                                                    Dialog.alert({
                                                        content: '点击遮罩关闭',
                                                        closeOnMaskClick: true,
                                                    })
                                                }}
                                            >
                                                修改
                                            </Button>
                                            <Button onClick={() => handleDelete(item.id)}>删除</Button>
                                        </div>
                                    </div>
                                )
                            })
                        )
                    }
                </div>
            </CommonPullToRefresh>
        </AnimatedTransition>
    )
}

export default CatesList;